<template>
  <a-modal
    title="添加業主"
    :width="900"
    class="model-yz"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item
          label="業主名稱"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-input placeholder="请输入業主名稱" v-decorator="['name', {rules: [{required: true, message: '请输入業主名稱！'}]}]" />
        </a-form-item>
        <a-form-item
          label="手機號"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-input placeholder="请输入手機號" v-decorator="['phone', {rules: [{required: true, message: '请输入手機號！'}]}]" />
        </a-form-item>
        <a-form-item
          label="相冊"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <div class="clearfix">
            <a-upload
                    :customRequest="customRequest1"
                    :multiple="false"
                    :showUploadList="false"
                    :before-upload="beforeUpload"
                    name="file">
                    <a-button><a-icon type="upload"/>上傳正面照片</a-button>
                  </a-upload>
            <a-row>
              <a-col :span="4" v-for="(item, index) in fileList" :key="index" class="parImg">
                 <a-icon type="delete" class="parImg_icon" @click="delImg(item.fileId)"/>
                 <img :src="item.url" style="max-width: 99%;width:100px"/>
              </a-col>
            </a-row>
          </div>
        </a-form-item>
        <a-divider/>
        <a-form-item
                label="簽約房間"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
              <a-input placeholder="簽約房間" :disabled="true"  v-decorator="['roomName', {rules: [{ required: true, message: '請選擇簽約房間！' }]}]">
                <a-icon slot="addonAfter" type="search" @click="onSelectRoom"/>
              </a-input>
        </a-form-item>
        <div>
                <a-form-item
                label="租期"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
                <a-date-picker
                  v-model="startValue"
                  :disabled-date="disabledStartDate"
                  format="YYYY-MM-DD"
                  placeholder="開始時間"
                  @openChange="handleStartOpenChange"
                />
                <a-date-picker
                  v-model="endValue"
                  :disabled-date="disabledEndDate"
                  format="YYYY-MM-DD"
                  placeholder="結束時間"
                  :open="endOpen"
                  @openChange="handleEndOpenChange"
                />
                <a-button style="margin-left: 10px;" type="dashed" size="small" :class="mocheck === 1 ? 'mocheck' : ''" @click="getEndTimeByStartTime(1)">一年</a-button>
                <a-button  type="dashed" size="small" :class="mocheck === 2 ? 'mocheck' : ''" @click="getEndTimeByStartTime(2)">兩年</a-button>
                <a-button  type="dashed" size="small" :class="mocheck === 3 ? 'mocheck' : ''" @click="getEndTimeByStartTime(3)">三年</a-button>
                <a-button  type="dashed" size="small" :class="mocheck === 4 ? 'mocheck' : ''" @click="getEndTimeByStartTime(4)">四年</a-button>
                </a-form-item>
        </div>
        <a-row :gutter="24">
              <a-form-item
              label="收租周期"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol">
              <a-input-group compact>
                <a-form-item
                    label=""
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol">
                  <a-select style="width: 150px" v-decorator="['receiptFu', { initialValue: 1, rules: [{ required: true, message: '请选择付款方式！' }]}]">
                    <a-select-option v-for="(item,index) in 18" :key="index" :value="item">付{{ item }}</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item
                    label=""
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol">
                  <a-select style="width: 150px" v-decorator="['receiptYa', { initialValue: 1, rules: [{ required: true, message: '请选择押金方式！' }]}]" @change="onReceiptyaChange">
                    <a-select-option v-for="(item,index) in 18" :key="index" :value="item">押{{ item }}</a-select-option>
                    <a-select-option :value="19">押金自定義</a-select-option>
                  </a-select>
                </a-form-item>
                 <a-form-item
                    label=""
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol">
                  <a-select style="width: 150px" v-decorator="['receiptYj', { initialValue: 3, rules: [{ required: true, message: '请选择付款周期！' }]}]">
                    <a-select-option :value="1">日</a-select-option>
                    <a-select-option :value="2">月</a-select-option>
                    <a-select-option :value="3">年</a-select-option>
                    <a-select-option :value="4">一次性付清</a-select-option>
                  </a-select>
                </a-form-item>
              </a-input-group>
            </a-form-item>
        </a-row>
        <a-form-item
          label="租金"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol">
        <a-input-number
              style="width:100%"
              placeholder="請輸入租金"
              :precision="2"
              :min="0"
              :max="99999999"
              :step="10"
              v-decorator="['rent', { initialValue: 0, rules: [{required: true, message: '請輸入租金'}]}]"
              @change="onRentChange"/>
        </a-form-item>
        <a-form-item
          label="押金"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol">
          <a-input-number
              style="width:100%"
              placeholder="請輸入每月押金"
              :precision="2"
              :min="0"
              :max="99999999"
              :step="10"
              v-decorator="['deposit', { initialValue: 0, rules: [{required: true, message: '請輸入押金'}]}]"/>
        </a-form-item>
        <a-form-item
          label="账单起始日"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol">
          <a-select style="width: 100%" placeholder="请选择賬單起始日" v-decorator="['billStart', { initialValue: 0 }]">
              <a-select-option :key="0" :value="0">起租日</a-select-option>
          </a-select>
         </a-form-item>
        <a-form-item
        label="提前几日"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol">
          <a-input-number
                        :min="0"
                        :max="365"
                        style="width:100%"
                        placeholder="请输入账单收租日提前几日"
                        v-decorator="['billEndTqData', { initialValue: 0 }]"/>
                        相较账单起始日提前几天交租
        </a-form-item>
        <a-divider/>
       <a-row>
          <a-table
              size="middle"
              :columns="columns"
              :dataSource="lszc"
              :pagination="false"
              :rowKey="(record) => record.rentAmountCategory"
              :loading="memberLoading">
          <template slot="amount" slot-scope="text, record">
                              <a-input-number
                                  style="width:100%"
                                  :precision="2"
                                  :min="0"
                                  :value="text"
                                  :max="99999999"
                                  @change="e => handlelszcChange(e,record.rentAmountCategory, 'amount')"
                                  :step="10"/>
                            </template>
                            <template slot="operation" slot-scope="text, record">
                              <a @click="lszcClick(record.rentAmountCategory)">删除</a>
                            </template>
          </a-table>
        </a-row>
        <a-button type="primary"  @click="lszcAddClick(2)" icon="plus" size="small" class="add_my">
          添加
        </a-button>
        <a-divider/>
         <a-form-item
          label="賬號類型"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol">
          <a-select style="width: 100%" placeholder="請選擇賬號類型"  v-decorator="['accountType', { initialValue: '1' }]"  @change="bankChange">
            <a-select-option v-for="(item,index) in accountTypeData" :key="index" :value="item.code">{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="持卡人"
          v-show="bankDisabled"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-input placeholder="請輸入持卡人" v-decorator="['cardHolder']" />
        </a-form-item>
        <a-form-item
          label="卡號"
          v-show="bankDisabled"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-input placeholder="請輸入卡號" v-decorator="['cardNumber']" />
        </a-form-item>
        <a-form-item
          label="開戶銀行"
          v-show="bankDisabled"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol">
          <a-select style="width: 100%" placeholder="請選擇開戶銀行"  v-decorator="['cardBankType']">
            <a-select-option v-for="(item,index) in cardBankTypeData" :key="index" :value="item.code">{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="賬號"
           v-show="!bankDisabled"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol">
          <a-input placeholder="請輸入賬號" v-decorator="['account']" />
        </a-form-item>
        <a-form-item
          label="收款人"
           v-show="!bankDisabled"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol">
          <a-input placeholder="請輸入收款人" v-decorator="['payee']" />
        </a-form-item>
        <a-form-item
          label="交租提醒"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-radio-group  v-decorator="['rentReminderSwitch', { initialValue: 1 }]" @change="rentReminderSwitchChange">
            <a-radio :value="1">開啟</a-radio>
            <a-radio :value="0">關閉</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
            v-show="onRentReminderSwitch"
                  label="收租提醒提前 天"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                >
                  <a-select  style="width: 100%" v-decorator="['rentReminderDay', { initialValue: 0 }]">
                    <a-select-option  style="width: 100%"  :value="0">當天</a-select-option>
                    <a-select-option  style="width: 100%"  v-for="(item,index) in 30" :key="index" :value="item">{{ item }}天</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item
                  v-show="false"
                  label="收租提醒提前 小時"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol">
                  <a-select  style="width: 100%" v-decorator="['rentReminderHour', { initialValue: 0 , rules: [{ required: true, message: '请选择收租提醒提前 小時！' }]}]">
                    <a-select-option  style="width: 100%"   :key="0" :value="0">0點</a-select-option>
                    <a-select-option  style="width: 100%"  v-for="(item,index) in 23" :key="index" :value="item">{{ item }}點</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item
                  v-show="false"
                  label="收租提醒提前 分鐘"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol">
                  <a-select  style="width: 100%" v-decorator="['rentReminderMinutes', { initialValue: 0 , rules: [{ required: true, message: '请选择收租提醒提前 分鐘！' }]}]">
                    <a-select-option  style="width: 100%"  :key="0" :value="0">0分</a-select-option>
                    <a-select-option  style="width: 100%"  v-for="(item,index) in 59" :key="index" :value="item">{{ item }}分</a-select-option>
                  </a-select>
                </a-form-item>
            <a-form-item
                  label="备注"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol">
                  <a-textarea placeholder="请输入備注" v-decorator="['remark']" />
                </a-form-item>
      </a-form>
    </a-spin>
    <bill-lszc-select ref="billLszcSelect" @ok="handleLszcOk"/>
    <room-select ref="roomSelect" @ok="handleSelectRoomOk" />
  </a-modal>
</template>

<script>
  import moment from 'moment'
  import { ownerLeaseAdd } from '@/api/modular/main/ownerlease/ownerLeaseManage'
  import { sysFileInfoUpload } from '@/api/modular/system/fileManage'
  import billLszcSelect from '../housebill/billLszcSelect.vue'
  import roomSelect from './roomSelect.vue'
  export default {
    components: {
      billLszcSelect,
      roomSelect
    },
    data () {
      return {
        labelCol_JG: {
          xs: { span: 24 },
          sm: { span: 3 }
        },
        wrapperCol_JG: {
          xs: { span: 24 },
          sm: { span: 20 }
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 }
        },
        rentStartDateDateString: '',
        rentEndDateDateString: '',
        cardBankTypeData: [],
        accountTypeData: [],
        rentReminderSwitchData: [],
        visible: false,
        bankDisabled: true,
        confirmLoading: false,
        memberLoading: false,
        form: this.$form.createForm(this),
        fileList: [],
        startValue: null,
        endValue: null,
        endOpen: false,
        mocheck: 3,
        columns: [
          {
            title: '名稱',
            dataIndex: 'rentAmountName',
            width: '30%',
            scopedSlots: { customRender: 'rentAmountName' }
          },
          {
            title: '金額',
            dataIndex: 'amount',
            width: '30%',
            scopedSlots: { customRender: 'amount' }
          },
          {
            title: '操作',
            key: 'action',
            scopedSlots: { customRender: 'operation' }
          }
        ],
        lszc: [],
        roomList: [],
        onRentReminderSwitch: true
      }
    },
    methods: {
      // 初始化方法
      add (record) {
        this.visible = true
        this.startValue = moment().format('YYYY-MM-DD')
        this.getEndTimeByStartTime(this.mocheck)
        const accountTypeOption = this.$options
        this.accountTypeData = accountTypeOption.filters['dictData']('account_type')
        const cardBankTypeOption = this.$options
        this.cardBankTypeData = cardBankTypeOption.filters['dictData']('card_bank_type')
        const rentReminderSwitchOption = this.$options
        this.rentReminderSwitchData = rentReminderSwitchOption.filters['dictData']('common_status')
      },
      onSelectRoom() {
        this.$refs.roomSelect.select()
      },
      handleSelectRoomOk (roomList) {
        this.roomList = roomList
        var roomstrnames = ''
        if (this.roomList.length > 2) {
           roomstrnames = this.roomList[0].name + ',' + this.roomList[1].name
        } else {
            for (var leni = 0; leni < this.roomList.length; leni++) {
                 roomstrnames = roomstrnames + this.roomList[leni].name + ','
            }
        }
        this.$nextTick(() => {
            this.form.setFieldsValue({
              roomName: roomstrnames
            })
        })
      },
      beforeUpload(file) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isJpgOrPng) {
          this.$message.error('只允許上傳圖片!')
        }
        const isLt2M = file.size / 1024 / 1024 < 6
        if (!isLt2M) {
          this.$message.error('圖片大小不允許超過6MB!')
        }
        return isJpgOrPng && isLt2M
      },
       /**
       * 上传文件
       */
      customRequest1 (data) {
        data.status = 'uploading'
        const formData = new FormData()
        formData.append('file', data.file)
        sysFileInfoUpload(formData).then((res) => {
          if (res.code === 200) {
            this.fileList.push({ fileId: res.data, url: '/api/sysFileInfo/preview?id=' + res.data })
          } else {
            this.$message.error('上传失败：' + res.msg)
          }
        })
      },
      delImg(id) {
        const newData = this.fileList.filter(item => item.fileId !== id)
        this.fileList = newData
      },
      disabledStartDate(startValue) {
        const endValue = this.endValue
        if (!startValue || !endValue) {
          return false
        }
        return startValue.valueOf() > endValue.valueOf()
      },
      disabledEndDate(endValue) {
        const startValue = this.startValue
        if (!endValue || !startValue) {
          return false
        }
        return startValue.valueOf() >= endValue.valueOf()
      },
      handleStartOpenChange(open) {
        if (!open) {
          this.endOpen = true
        }
      },
      handleEndOpenChange(open) {
        this.endOpen = open
      },
      getEndTimeByStartTime(type) {
        this.mocheck = type
        this.endValue = moment(this.startValue).add(type, 'years').subtract(1, 'days').format('YYYY-MM-DD')
      },
       // 租金点击事件
      onRentChange(value) {
        const receiptya = this.form.getFieldValue('receiptYa')
        if (receiptya === 19) {
          this.$nextTick(() => {
            this.form.setFieldsValue({
              deposit: value
            })
          })
        } else {
          this.$nextTick(() => {
            this.form.setFieldsValue({
              deposit: value * receiptya
            })
          })
        }
      },
      // 押金点击事件
      onReceiptyaChange(value) {
        if (value !== 19) {
         const rent = this.form.getFieldValue('rent')
         const rentPrice = value * rent
          this.$nextTick(() => {
            this.form.setFieldsValue({
              deposit: rentPrice
            })
          })
        }
      },
      handlelszcChange (value, key, column) {
        const newData = [...this.lszc]
        const target = newData.find(item => key === item.rentAmountCategory)
        if (target) {
          target[column] = value
          this.lszc = newData
        }
      },
      /**
       * 删除
       */
      lszcClick(key) {
        const newData = this.lszc.filter(item => item.rentAmountCategory !== key)
        this.lszc = newData
      },
      lszcAddClick(type) {
        this.$refs.billLszcSelect.select(this.lszc, 2)
      },
      handleLszcOk(values, type) {
        if (type === 2) {
          if (values.length > 0) {
            const chllenLen = values.length
            for (var iv = 0; iv < chllenLen; iv++) {
              const target = this.lszc.find(item => values[iv].rentAmountCategory === item.rentAmountCategory)
              if (!target) {
                this.lszc.push(values[iv])
              }
            }
          }
        }
      },
      bankChange(value) {
        if (value === '1') {
          this.bankDisabled = true
        } else {
          this.bankDisabled = false
        }
      },
      rentReminderSwitchChange() {
        this.onRentReminderSwitch = !this.onRentReminderSwitch
      },
      /**
       * 提交表单
       */
      handleSubmit () {
        if (this.roomList.length === 0) {
           this.$message.error('請選擇簽約房間')
          return false
        }
        if (!(this.startValue && this.endValue)) {
              this.$message.error('租期開始時間結束時間不允許爲空！')
              return false
        }
        if (this.startValue.valueOf() >= this.endValue.valueOf()) {
              this.$message.error('租期開始時間不允許大於結束時間！')
              return false
        }
        const { form: { validateFields } } = this
        this.confirmLoading = true
        validateFields((errors, values) => {
          if (!errors) {
            for (const key in values) {
              if (typeof (values[key]) === 'object') {
                values[key] = JSON.stringify(values[key])
              }
            }
            values.rentStartDate = moment(this.startValue).format('YYYY-MM-DD')
            values.rentEndDate = moment(this.endValue).format('YYYY-MM-DD')
            values.roomList = this.roomList
            values.files = this.fileList
            values.gdfy = this.lszc
            ownerLeaseAdd(values).then((res) => {
              if (res.code === 200) {
                this.$message.success('新增成功')
                this.confirmLoading = false
                this.$emit('ok', values)
                this.handleCancel()
              } else {
                this.$message.error('新增失败')// + res.message
              }
            }).finally((res) => {
              this.confirmLoading = false
            })
          } else {
            this.confirmLoading = false
          }
        })
      },
      onChangerentStartDate(date, dateString) {
        this.rentStartDateDateString = dateString
      },
      onChangerentEndDate(date, dateString) {
        this.rentEndDateDateString = dateString
      },
      handleCancel () {
        this.form.resetFields()
        this.visible = false
        this.fileList = []
        this.startValue = null
        this.endValue = null
        this.endOpen = false
        this.lszc = []
        this.roomList = []
        this.bankDisabled = true
        this.onRentReminderSwitch = true
      }
    }
  }
</script>
<style lang="less" scoped >
.model-yz  /deep/ .ant-modal-content{
    height: 1000px;
    overflow-y:scroll;
    overflow-x: hidden;
}
.model-yz  /deep/ .ant-modal-content::-webkit-scrollbar {
  width: 4px;
}
.model-yz  /deep/ .ant-modal-content::-webkit-scrollbar-track {
 background-color:rgb(250, 241, 241);
}
.model-yz  /deep/ .ant-modal-content::-webkit-scrollbar-thumb {
 background-color:rgb(205, 209, 205);
}
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.parImg{
  position: relative;
}
.parImg_icon{
  position: absolute;
  top: 0;
  right: 0;
  color: rgba(255, 0, 0, 0.829);
}
.mocheck{
  background-color: rgba(58, 136, 180, 0.822);
  color: aliceblue;
}
</style>
